package cs6238.common;

import java.nio.ByteBuffer;

public class ByteArray {

	public static int readInt(byte[] buffer){
		ByteBuffer bb = ByteBuffer.wrap(buffer);
		return bb.getInt();
	}
	
	public static byte[] writeInt(int i){
		ByteBuffer bb = ByteBuffer.wrap(new byte[4]);
		bb.putInt(i);
		return bb.array();
	}
	
	public static byte[] writeString(String str){
		byte[] b_str = str.getBytes();
		ByteBuffer bb = ByteBuffer.wrap(new byte[4 + b_str.length]);
		bb.putInt(b_str.length);
		bb.put(b_str);
		return bb.array();
		
	}

	public static String readString(ByteBuffer bb){
		byte[] b_str = new byte[bb.getInt()];
		bb.get(b_str);
		return new String(b_str);
	}
	
	
	/**
	 * When the signature is written to CSV, it is stored as a hex string
	 * Java doesn't play well with mixing strings and bytes sometimes
	 */
	private static final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();
	
	public static String toHexString(byte[] buffer){
		StringBuffer strBuffer = new StringBuffer();
		for(byte b : buffer){
			strBuffer.append(HEX_CHARS[0xF & b]);
			strBuffer.append(HEX_CHARS[0xF & (b >> 4)]);
		}
		return strBuffer.toString();
	}
	
	public static byte[] fromHexString(String hexString){
		byte[] result = new byte[hexString.length()/2];
		for(int i=0; i<result.length; i++){
			char c = hexString.charAt(i * 2);
			char d = hexString.charAt(i * 2 + 1);
		
			result[i] = valueOfHexChar(c);
			result[i] |= valueOfHexChar(d) << 4; 
		}
		
		return result;
	}
	
	private static byte valueOfHexChar(char c){
		int val = c - '0';
		if(val >=0 && val <= 9){
			return (byte) val;
		}
		return (byte)(c - 'A' + 10);
	}
}
